<template>
  <a-spin :spinning="spinning">
    <div style="background:white;">
      <a-tabs default-active-key="all"  @change="tabCallback" :tabBarStyle="{padding:'0px 10px'}">
        <a-tab-pane key="all" tab="全部"></a-tab-pane>
        <a-tab-pane :key="0" tab="客户关系维护"></a-tab-pane>
        <a-tab-pane :key="1" tab="台账进度管理"></a-tab-pane>
        <a-tab-pane :key="2" tab="客户节点信息"></a-tab-pane>
        <a-tab-pane :key="3" tab="技术TR不满足项"></a-tab-pane>
        <a-tab-pane :key="4" tab="客户关系图"></a-tab-pane>
        <a-tab-pane :key="5" tab="自定义"></a-tab-pane>
      </a-tabs>
      <a-calendar :header-render="headerRender" v-model="calendarValue" >
        <template slot="dateCellRender" slot-scope="value">
          <a-dropdown :trigger="['contextmenu']">
            <ul class="events" v-if="backlogList[getDateFormat(value)]" @dblclick="handleDbclick">
              <li v-for="(item,i) in backlogList[getDateFormat(value)] || []" :key="i">
                <a-badge status="success" v-if="item.status === '已完成'" :text="item.record" />
                <a-badge status="warning" v-else-if="item.status === '未完成' && !isTimeOut(item)" :text="item.record" />
                <a-badge status="error" v-else-if="item.status === '未完成' && isTimeOut(item)" :text="item.record" />
              </li>
            </ul>
            <div style="height:100%;width:100%;"  @dblclick="handleDbclick" v-else></div>
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="handleDetail(value)">
                详情
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-calendar>
    </div>
    <pending-work-modal
      ref="pendingWorkModal"
      :calendarValue="calendarValue"
      :currentTab="currentTab"
      @init="init"
    >
    </pending-work-modal>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import moment from 'moment'
import pendingWorkModal from './modal/pendingWorkModal'
import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUser'
import { mapGetters } from 'vuex'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'pendingWork',
  components: {
    pendingWorkModal,
    JSelectMultiUser
  },
  data() {
    return {
      spinning: false,
      url: {
        backlogList: '/backlog/queryBacklogList',
        executeJob: '/sys/quartzJob/executeByJobClassName'
      },
      backlogList: {}, // 按日期转换后的数据
      calendarValue: moment(new Date()),
      currentTab: 'all',
      multiUser: '',
      realname: '',
      yearOptions: []// 系统年份
    }
  },
  watch: {
    calendarValue: {
      handler(newVal) {
        this.init(false)
      },
      deep: true
    },
    multiUser(newVal) { // 监听用户变化查询待办
      this.init(true)
    }
  },
  mounted() {
    this.multiUser = this.userInfo().username
    this.realname = this.userInfo().realname
    this.init(true)
    initDictOptions('year_value').then(res => {
      this.yearOptions = res.result
    })
  },
  methods: {
    ...mapGetters(['userInfo']),
    handleExecute() {
      this.spinning = true
      const param = ['org.jeecg.business.webapp.quartz.job.AsyncBacklogJob']
      getAction(this.url.executeJob, { jobClassName: param.join(',') }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.init(true)
        } else {
          this.$message.error(res.message)
          this.spinning = false
        }
      })
    },
    handleDbclick() {
      this.$refs.pendingWorkModal.init()
      this.$refs.pendingWorkModal.editModalVisible = true
    },
    init(spinning) {
      this.spinning = spinning// 通过传值控制点击切换时不显示loading
      const year = this.calendarValue.year()
      const month = this.calendarValue.month() + 1
      const lastDay = new Date(year, month, 0).getDate()
      getAction(this.url.backlogList, {// 获取当月待办工作
        startTime: year + '-' + month + '-1' + ' 00:00:00',
        endTime: year + '-' + month + '-' + lastDay + ' 23:59:59',
        userId: this.multiUser,
        isCurrentDay: 0,
        dataType: this.currentTab === 'all' ? '' : this.currentTab
      }).then(res => {
        this.spinning = false
        if (res.success) {
          this.getBacklogList(res.result)
        }
      })
    },
    getBacklogList(list) { // 把请求回的数据按日期转换为对象
      this.backlogList = {}
      list.forEach(item => {
        if (item.planTime) {
          const key = moment(item.planTime).format('YYYY-MM-DD')
          this.backlogList[key] ? this.backlogList[key].push(item) : this.backlogList[key] = [item]
        }
      })
    },
    getDateFormat(value) {
      return moment(value).format('YYYY-MM-DD')
    },
    handleDetail(value) {
      this.calendarValue = moment(value)
      setTimeout(() => {
        this.$refs.pendingWorkModal.editModalVisible = true
        this.$refs.pendingWorkModal.init()
      }, 100)
    },
    headerRender({ value, type, onChange, onTypeChange }) { // 自定义日历头   取消年月切换
      const start = 0
      const end = 12
      const monthOptions = []
      const current = value.clone()
      const localeData = value.localeData()
      const months = []
      for (let i = 0; i < 12; i++) {
        current.month(i)
        months.push(localeData.monthsShort(current))
      }

      for (let index = start; index < end; index++) {
        monthOptions.push(
          <a-select-option class='month-item' key={`${index}`}>
            {months[index]}
          </a-select-option>,
        )
      }
      const month = value.month()
      const year = value.year()
      const options = []
      for (let i = 0; i < this.yearOptions.length; i += 1) {
        options.push(
          <a-select-option key={i} value={this.yearOptions[i].value} class='year-item'>
            {this.yearOptions[i].text}
          </a-select-option>,
        )
      }
      return (
        <div style={{ padding: '10px' }}>
          <a-row type='flex' gutter={16} justify='end'>

            <a-col>
              <a-select
                dropdownMatchSelectWidth={false}
                class='my-year-select'
                style={{ width: '100px' }}
                onChange={newYear => {
                  const now = value.clone().year(newYear)
                  onChange(now)
                }}
                value={String(year)}
              >
                {options}
              </a-select>
            </a-col>
            <a-col>
              <a-select
                dropdownMatchSelectWidth={false}
                value={String(month)}
                style={{ width: '100px' }}
                onChange={selectedMonth => {
                  const newValue = value.clone()
                  newValue.month(parseInt(selectedMonth, 10))
                  onChange(newValue)
                }}
              >
                {monthOptions}
              </a-select>
            </a-col>
            <a-col>
              <a-button-group>
                <a-button onClick={() => { this.preMonth() }}> <a-icon type='left' />上一月</a-button>
                <a-button onClick={() => { this.nextMonth() }}>下一月<a-icon type='right' /></a-button>
              </a-button-group>
            </a-col>
            <a-col v-has='user:appoint_user_search'>
              <j-dict-select-tag v-model={this.multiUser} placeholder='请选择用户' class='dict-select' dict-code='ys_appoint_user'/>
            </a-col>
            <a-col v-has='user:search'>
              <j-select-multi-user onSelect={(rows) => { this.getRealname(rows) }} v-model={this.multiUser} style='width:300px;'></j-select-multi-user>
            </a-col>
            <a-col>
              <a-button type='primary' onClick={() => { this.handleExecute() }}>立即执行</a-button>
            </a-col>
          </a-row>
        </div>
      )
    },
    tabCallback(activeKey) {
      this.currentTab = activeKey
      this.init(true)
    },
    isTimeOut(data) { // 判断是否超时
      const curentDate = new Date(data.server_time)
      const planDate = new Date(data.planTime)
      return curentDate.getTime() > planDate.getTime()
    },
    getRealname(rows) {
      const realnames = []
      rows.map(item => {
        realnames.push(item.realname)
      })
      this.realname = realnames.join(',')
    },
    nextMonth() {
      var month = this.calendarValue.month() + 1
      var year = this.calendarValue.year()
      if (month < 12) {
        ++month
      } else {
        ++year
        month = 1
      }
      this.calendarValue = moment(year + '-' + month + '-' + 1)
    },
    preMonth() {
      var month = this.calendarValue.month() + 1
      var year = this.calendarValue.year()
      if (month === 1) {
        --year
        month = 12
      } else {
        --month
      }
      this.calendarValue = moment(year + '-' + month + '-' + 1)
    }
  }
}
</script>
<style>
.warp .ant-fullcalendar-fullscreen .ant-fullcalendar-month,
.warp .ant-fullcalendar-fullscreen .ant-fullcalendar-date
{
  height:100px;
}
.warp .ant-fullcalendar-fullscreen .ant-fullcalendar-content{
  height:72px;
}
.warp .ant-fullcalendar-column-header{
  background: rgb(234, 234, 234);
  border: 1px solid white;
}
.ant-fullcalendar .ant-fullcalendar-calendar-body thead tr{
  height: 40px;
}
</style>
<style scoped>
.events {
  height:100%;
  list-style: none;
  margin: 0;
  padding: 0;
}
.events .ant-badge-status {
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
  text-overflow: ellipsis;
  font-size: 12px;
}
.notes-month {
  text-align: center;
  font-size: 28px;
}
.notes-month section {
  font-size: 28px;
}
.dict-select{
  width: 150px;
}
</style>
